package com;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 可以指定并发的线程数量控制
 * 可以用于多个共享资源的互斥使用
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "在执行");
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    semaphore.release();
                }
            },i + "").start();
        }
    }
}
